import os
import sys
import traceback
from datetime import datetime

import mysql.connector
import openpyxl
import pandas as pd
from mysql.connector import Error
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QLabel, QPushButton, QTableWidget, QTableWidgetItem, QHeaderView,
    QMessageBox, QDialog, QDialogButtonBox, QFormLayout, QComboBox,
    QLineEdit, QDoubleSpinBox, QCheckBox, QGroupBox, QRadioButton, QFileDialog
)
from PyQt5.QtGui import QColor, QBrush, QFont, QIcon
from PyQt5.QtCore import Qt
from openpyxl.styles import Side, Alignment, PatternFill, Border, Font

# 直接导入您提供的CardManager类
from Manage.bank_card_manager import CardManager  # 替换为实际导入路径
from Manage.deposit_manager import DepositManager


class DBUtils:
    """数据库工具类 - 增加实时数据支持"""

    def connect(self):
        """连接到MySQL数据库 - 增加事务隔离级别设置"""
        try:
            if self.connection and self.connection.is_connected():
                return True

            self.connection = mysql.connector.connect(
                host='localhost',
                database='bank system',
                user='root',
                password='1234',
                autocommit=True,  # 启用自动提交
                isolation_level='READ COMMITTED'  # 设置为读已提交级别
            )

            if self.connection.is_connected():
                # 设置会话变量确保实时数据
                cursor = self.connection.cursor()
                cursor.execute("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED")
                cursor.execute("SET SESSION innodb_lock_wait_timeout = 50")
                cursor.close()
                return True
            return False
        except Error as e:
            print(f"数据库连接失败: {e}")
            return False

    def execute_query(self, query, params=None, fetch=True):
        """执行SQL查询 - 确保实时结果"""
        cursor = None
        try:
            if not self.connect():
                return None

            # 创建新游标确保最新数据
            cursor = self.connection.cursor(dictionary=True)

            # 添加FOR UPDATE SKIP LOCKED避免锁等待
            if "SELECT" in query.upper() and "FOR UPDATE" not in query.upper():
                query += " FOR UPDATE SKIP LOCKED"

            # 执行查询
            cursor.execute(query, params or ())

            if fetch:
                result = cursor.fetchall()
                # 立即提交事务确保后续查询能看到最新数据
                self.connection.commit()
                return result
            else:
                self.connection.commit()
                return True
        except Error as e:
            if self.connection:
                self.connection.rollback()
            return None
        finally:
            if cursor:
                cursor.close()

class DepositTypeDialog(QDialog):
    """存款类型管理对话框"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.deposit_manager = DepositManager()
        self.setWindowTitle("存款类型管理")
        self.setFixedSize(600, 400)
        self.setup_ui()
        self.load_deposit_types()

    def setup_ui(self):
        """初始化界面"""
        layout = QVBoxLayout()

        # 存款类型表格
        self.table = QTableWidget()
        self.table.setColumnCount(3)
        self.table.setHorizontalHeaderLabels(["ID", "存款类型名称", "描述"])
        self.table.setSelectionBehavior(QTableWidget.SelectRows)
        self.table.setEditTriggers(QTableWidget.NoEditTriggers)

        # 操作按钮
        btn_layout = QHBoxLayout()
        self.add_btn = QPushButton("添加")
        self.edit_btn = QPushButton("编辑")
        self.delete_btn = QPushButton("删除")
        self.refresh_btn = QPushButton("刷新")
        self.close_btn = QPushButton("关闭")

        btn_layout.addWidget(self.add_btn)
        btn_layout.addWidget(self.edit_btn)
        btn_layout.addWidget(self.delete_btn)
        btn_layout.addStretch()
        btn_layout.addWidget(self.refresh_btn)
        btn_layout.addWidget(self.close_btn)

        layout.addWidget(self.table)
        layout.addLayout(btn_layout)
        self.setLayout(layout)

        # 连接信号
        self.add_btn.clicked.connect(self.add_deposit_type)
        self.edit_btn.clicked.connect(self.edit_deposit_type)
        self.delete_btn.clicked.connect(self.delete_deposit_type)
        self.refresh_btn.clicked.connect(self.load_deposit_types)
        self.close_btn.clicked.connect(self.close)

    def load_deposit_types(self):
        """加载存款类型数据"""
        try:
            deposit_types = self.deposit_manager.get_all_deposit_types()
            self.table.setRowCount(len(deposit_types))

            for row, deposit in enumerate(deposit_types):
                self.table.setItem(row, 0, QTableWidgetItem(str(deposit['savingID'])))
                self.table.setItem(row, 1, QTableWidgetItem(deposit['savingName']))
                self.table.setItem(row, 2, QTableWidgetItem(deposit.get('descrip', '')))

                # 设置文本居中
                for col in range(3):
                    self.table.item(row, col).setTextAlignment(Qt.AlignCenter)
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载存款类型失败: {str(e)}")

    def get_selected_deposit_id(self):
        """获取选中存款类型ID"""
        row = self.table.currentRow()
        if row < 0:
            return None
        return int(self.table.item(row, 0).text())

    def add_deposit_type(self):
        """添加存款类型"""
        dialog = QDialog(self)
        dialog.setWindowTitle("添加存款类型")
        dialog.setFixedSize(400, 200)

        # 表单控件
        name_input = QLineEdit()
        name_input.setMaxLength(20)
        desc_input = QLineEdit()

        # 按钮
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(dialog.accept)
        button_box.rejected.connect(dialog.reject)

        # 布局
        layout = QFormLayout()
        layout.addRow("存款类型名称:", name_input)
        layout.addRow("描述:", desc_input)
        layout.addRow(button_box)
        dialog.setLayout(layout)

        if dialog.exec_() == QDialog.Accepted:
            if not name_input.text().strip():
                QMessageBox.warning(self, "错误", "存款类型名称不能为空")
                return

            if self.deposit_manager.add_deposit_type(
                    name_input.text().strip(),
                    desc_input.text().strip() or None
            ):
                self.load_deposit_types()

    def edit_deposit_type(self):
        """编辑存款类型"""
        deposit_id = self.get_selected_deposit_id()
        if not deposit_id:
            QMessageBox.warning(self, "警告", "请先选择要编辑的存款类型")
            return

        # 获取当前值
        row = self.table.currentRow()
        current_name = self.table.item(row, 1).text()
        current_desc = self.table.item(row, 2).text()

        dialog = QDialog(self)
        dialog.setWindowTitle("编辑存款类型")
        dialog.setFixedSize(400, 200)

        # 表单控件
        name_input = QLineEdit(current_name)
        name_input.setMaxLength(20)
        desc_input = QLineEdit(current_desc)

        # 按钮
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(dialog.accept)
        button_box.rejected.connect(dialog.reject)

        # 布局
        layout = QFormLayout()
        layout.addRow("存款类型名称:", name_input)
        layout.addRow("描述:", desc_input)
        layout.addRow(button_box)
        dialog.setLayout(layout)

        if dialog.exec_() == QDialog.Accepted:
            if not name_input.text().strip():
                QMessageBox.warning(self, "错误", "存款类型名称不能为空")
                return

            if self.deposit_manager.update_deposit_type(
                    deposit_id,
                    name_input.text().strip(),
                    desc_input.text().strip() or None
            ):
                self.load_deposit_types()

    def delete_deposit_type(self):
        """删除存款类型"""
        deposit_id = self.get_selected_deposit_id()
        if not deposit_id:
            QMessageBox.warning(self, "警告", "请先选择要删除的存款类型")
            return

        reply = QMessageBox.question(
            self, "确认删除",
            "确定要删除此存款类型吗？此操作不可恢复！",
            QMessageBox.Yes | QMessageBox.No
        )

        if reply == QMessageBox.Yes:
            if self.deposit_manager.delete_deposit_type(deposit_id):
                self.load_deposit_types()
            else:
                QMessageBox.warning(self, "失败", "删除存款类型失败，可能有关联银行卡")

class CardDialog(QDialog):
    """银行卡信息对话框 - 新增客户ID输入功能"""

    def __init__(self, card=None, customer_id=None, parent=None):
        super().__init__(parent)
        self.card = card
        self.customer_id = customer_id
        self.deposit_manager = DepositManager()  # 存款类型管理器
        self.setWindowTitle("编辑银行卡" if card else "添加新银行卡")
        self.setFixedSize(600, 550)  # 增加高度以容纳新字段

        # 初始化UI组件
        self.setup_ui()

        # 填充现有数据（如果是编辑模式）
        if card:
            self.populate_fields()
        else:
            # 设置默认值
            self.password_input.setText("888888")
            self.password_input.setEchoMode(QLineEdit.Password)
            self.open_money_spin.setValue(1.0)
            self.balance_spin.setValue(1.0)
            self.is_report_loss_combo.setCurrentText("否")

            # 设置客户ID输入框的值
            if self.customer_id:
                self.customer_id_input.setText(str(self.customer_id))

        # 加载存款类型数据
        self.load_deposit_types()

    def setup_ui(self):
        """初始化界面组件"""
        layout = QFormLayout()
        layout.setSpacing(15)
        layout.setContentsMargins(15, 15, 15, 15)

        # === 新增客户ID输入行 ===
        self.customer_id_input = QLineEdit()
        self.customer_id_input.setPlaceholderText("输入客户ID")
        if self.card:  # 编辑模式下禁用客户ID修改
            self.customer_id_input.setReadOnly(True)
        layout.addRow("客户ID:", self.customer_id_input)

        # 卡号输入
        self.card_id_input = QLineEdit()
        self.card_id_input.setMaxLength(16)
        self.card_id_input.setPlaceholderText("16位数字")
        if self.card:  # 编辑模式下禁用卡号修改
            self.card_id_input.setReadOnly(True)

        # 货币类型下拉框
        self.cur_id_combo = QComboBox()
        self.cur_id_combo.addItems(["RMB(￥)", "JPY(￥)", "USD($)"])

        # 存款类型下拉框
        self.saving_type_combo = QComboBox()
        self.saving_type_combo.setMinimumWidth(200)

        # 存款类型管理按钮
        self.manage_deposit_btn = QPushButton("管理存款类型...")
        self.manage_deposit_btn.setFixedWidth(120)
        self.manage_deposit_btn.clicked.connect(self.manage_deposit_types)

        # 金额输入
        self.open_money_spin = QDoubleSpinBox()
        self.open_money_spin.setRange(1.0, 1000000.0)
        self.open_money_spin.setPrefix("¥ ")
        self.open_money_spin.setDecimals(2)

        self.balance_spin = QDoubleSpinBox()
        self.balance_spin.setRange(1.0, 1000000.0)
        self.balance_spin.setPrefix("¥ ")
        self.balance_spin.setDecimals(2)

        # 密码输入
        self.password_input = QLineEdit()
        self.password_input.setMaxLength(6)
        self.password_input.setEchoMode(QLineEdit.Password)
        self.show_password_check = QCheckBox("显示密码")
        self.show_password_check.stateChanged.connect(self.toggle_password_visibility)

        # 是否挂失
        self.is_report_loss_combo = QComboBox()
        self.is_report_loss_combo.addItems(["是", "否"])

        # 按钮
        self.button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.button_box.accepted.connect(self.validate_and_accept)
        self.button_box.rejected.connect(self.reject)

        # 组装布局
        layout.addRow("卡号 (16位):", self.card_id_input)
        layout.addRow("货币类型:", self.cur_id_combo)

        # 存款类型行布局
        deposit_layout = QHBoxLayout()
        deposit_layout.addWidget(self.saving_type_combo)
        deposit_layout.addWidget(self.manage_deposit_btn)
        layout.addRow("存款类型:", deposit_layout)

        layout.addRow("开户金额:", self.open_money_spin)
        layout.addRow("当前余额:", self.balance_spin)

        # 密码行布局
        password_layout = QHBoxLayout()
        password_layout.addWidget(self.password_input)
        password_layout.addWidget(self.show_password_check)
        layout.addRow("密码 (6位):", password_layout)

        layout.addRow("是否挂失:", self.is_report_loss_combo)
        layout.addRow(self.button_box)

        self.setLayout(layout)

    def load_deposit_types(self):
        """加载存款类型到下拉框 - 增加描述显示"""
        try:
            self.saving_type_combo.clear()
            deposit_types = self.deposit_manager.get_all_deposit_types()

            for deposit in deposit_types:
                # 在显示中添加描述信息
                display_text = f"{deposit['savingName']} (ID:{deposit['savingID']})"
                if deposit.get('descrip'):
                    display_text += f" - {deposit['descrip']}"

                self.saving_type_combo.addItem(
                    display_text,
                    userData=deposit['savingID']
                )

            # 如果是编辑模式，设置当前选中的存款类型
            if self.card:
                saving_id = str(self.card.get('savingID', ''))
                for i in range(self.saving_type_combo.count()):
                    if str(self.saving_type_combo.itemData(i)) == saving_id:
                        self.saving_type_combo.setCurrentIndex(i)
                        break

        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载存款类型失败: {str(e)}")

    def manage_deposit_types(self):
        """打开存款类型管理对话框"""
        dialog = DepositTypeDialog(self)
        if dialog.exec_() == QDialog.Accepted:
            self.load_deposit_types()  # 刷新下拉框

    def toggle_password_visibility(self, state):
        """切换密码显示/隐藏"""
        if state == Qt.Checked:
            self.password_input.setEchoMode(QLineEdit.Normal)
        else:
            self.password_input.setEchoMode(QLineEdit.Password)

    def populate_fields(self):
        """填充银行卡数据（编辑模式）"""
        # 填充客户ID
        self.customer_id_input.setText(str(self.card.get('customerID', '')))

        # 填充其他字段
        self.card_id_input.setText(self.card.get('cardID', ''))
        self.cur_id_combo.setCurrentText(self.card.get('curID', '01'))
        self.open_money_spin.setValue(float(self.card.get('openMoney', 1.0)))
        self.balance_spin.setValue(float(self.card.get('balance', 1.0)))
        self.password_input.setText(self.card.get('pass', '888888'))
        self.password_input.setEchoMode(QLineEdit.Normal)  # 编辑时默认显示明文
        self.show_password_check.setChecked(True)  # 默认勾选显示密码
        self.is_report_loss_combo.setCurrentText(self.card.get('IsReportLoss', '否'))

    def validate_and_accept(self):
        """验证表单数据 - 增加客户ID验证"""
        errors = []

        # 验证客户ID
        customer_id = self.customer_id_input.text().strip()
        if not customer_id:
            errors.append("客户ID不能为空")
        elif not customer_id.isdigit():
            errors.append("客户ID必须为数字")

        # 验证卡号
        card_id = self.card_id_input.text().strip()
        if not card_id or len(card_id) != 16 or not card_id.isdigit():
            errors.append("卡号必须为16位数字")

        # 验证密码
        password = self.password_input.text().strip()
        if not password or len(password) != 6 or not password.isdigit():
            errors.append("密码必须为6位数字")

        # 验证金额
        if self.open_money_spin.value() < 1.0:
            errors.append("开户金额不能小于1元")

        # 验证存款类型
        if self.saving_type_combo.currentIndex() < 0:
            errors.append("请选择存款类型")

        if errors:
            QMessageBox.warning(self, "表单验证失败", "\n".join(errors))
            return

        self.accept()

    def get_values(self):
        """获取表单数据 - 使用输入框中的客户ID"""
        customer_id = self.customer_id_input.text().strip()

        return {
            'card_id': self.card_id_input.text().strip(),
            'cur_id': self.cur_id_combo.currentText(),
            'saving_id': self.saving_type_combo.currentData(),
            'customer_id': customer_id,
            'open_money': float(self.open_money_spin.value()),
            'balance': float(self.balance_spin.value()),
            'password': self.password_input.text().strip(),
            'is_report_loss': self.is_report_loss_combo.currentText()
        }

class CardManagementTab(QWidget):
    """银行卡管理主界面 - 集成查询功能"""

    COLUMNS = ["卡号", "货币类型", "存款类型", "客户ID", "开户金额", "余额", "是否挂失"]

    def __init__(self, customer_id=None, parent=None):
        super().__init__(parent)
        self.customer_id = customer_id
        self.manager = CardManager()
        self.setup_ui()
        self.load_cards()

        # 设置样式
        self.setStyleSheet("""
            QLineEdit {
                padding: 5px;
                border: 1px solid #ddd;
                border-radius: 3px;
            }
            QPushButton {
                padding: 5px 10px;
                min-width: 70px;
            }
            QComboBox {
                padding: 3px;
            }
        """)

    def get_selected_card_id(self):
        """获取当前选中的银行卡 ID"""
        selected_row = self.table.currentRow()
        if selected_row < 0:
            return None
        return self.table.item(selected_row, 0).text()

    def setup_ui(self):
        """初始化界面组件"""
        layout = QVBoxLayout()
        layout.setContentsMargins(10, 10, 10, 10)
        layout.setSpacing(10)

        # 客户信息显示（如果指定了客户ID）
        if self.customer_id:
            info_label = QLabel(f"当前客户ID: {self.customer_id}")
            info_label.setStyleSheet("font-weight: bold; color: #333;")
            layout.addWidget(info_label)

        self.export_btn = QPushButton("导出报表")
        self.export_btn.setIcon(QIcon.fromTheme("document-export"))
        self.export_btn.setToolTip("导出当前银行卡数据为报表")

        # === 新增搜索区域 ===
        search_group = QGroupBox("银行卡查询")
        search_group.setStyleSheet("QGroupBox { border: 1px solid #eee; padding-top: 15px; }")
        search_layout = QVBoxLayout()

        # 快速搜索行
        quick_search_layout = QHBoxLayout()
        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("输入卡号/客户ID/货币类型...")
        self.search_input.setClearButtonEnabled(True)
        self.search_input.returnPressed.connect(self.search_cards)

        self.search_btn = QPushButton("搜索")
        self.search_btn.setIcon(QIcon.fromTheme("system-search"))
        self.search_btn.clicked.connect(self.search_cards)

        self.adv_search_btn = QPushButton("高级搜索")
        self.adv_search_btn.setIcon(QIcon.fromTheme("preferences-system"))
        self.adv_search_btn.clicked.connect(self.show_advanced_search)

        self.reset_btn = QPushButton("重置")
        self.reset_btn.setIcon(QIcon.fromTheme("edit-clear"))
        self.reset_btn.clicked.connect(self.load_cards)

        quick_search_layout.addWidget(self.search_input)
        quick_search_layout.addWidget(self.search_btn)
        quick_search_layout.addWidget(self.adv_search_btn)
        quick_search_layout.addWidget(self.reset_btn)

        # 状态标签
        self.status_label = QLabel("就绪")
        self.status_label.setStyleSheet("color: #666; font-style: italic;")

        search_layout.addLayout(quick_search_layout)
        search_layout.addWidget(self.status_label)
        search_group.setLayout(search_layout)
        layout.addWidget(search_group)
        # === 搜索区域结束 ===

        # 操作按钮区域
        btn_layout = QHBoxLayout()
        self.add_btn = QPushButton("添加银行卡")
        self.add_btn.setIcon(QIcon.fromTheme("list-add"))
        self.edit_btn = QPushButton("编辑银行卡")
        self.edit_btn.setIcon(QIcon.fromTheme("document-edit"))
        self.delete_btn = QPushButton("删除银行卡")
        self.delete_btn.setIcon(QIcon.fromTheme("list-remove"))
        self.refresh_btn = QPushButton("刷新")
        self.refresh_btn.setIcon(QIcon.fromTheme("view-refresh"))

        btn_layout.addWidget(self.add_btn)
        btn_layout.addWidget(self.edit_btn)
        btn_layout.addWidget(self.delete_btn)
        btn_layout.addStretch()
        btn_layout.addWidget(self.export_btn)  # 添加导出按钮
        btn_layout.addWidget(self.refresh_btn)

        # 银行卡表格
        self.table = QTableWidget()
        self.table.setColumnCount(len(self.COLUMNS))
        self.table.setHorizontalHeaderLabels(self.COLUMNS)
        self.table.setSelectionBehavior(QTableWidget.SelectRows)
        self.table.setSelectionMode(QTableWidget.SingleSelection)
        self.table.setEditTriggers(QTableWidget.NoEditTriggers)

        # 设置表格样式
        self.table.setStyleSheet("""
            QTableWidget {
                alternate-background-color: #f9f9f9;
            }
            QHeaderView::section {
                background-color: #f0f0f0;
                padding: 5px;
                border: none;
            }
        """)

        # 设置列宽
        header = self.table.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.ResizeToContents)  # 卡号
        header.setSectionResizeMode(1, QHeaderView.ResizeToContents)  # 货币类型
        header.setSectionResizeMode(2, QHeaderView.Stretch)  # 存款类型
        header.setSectionResizeMode(3, QHeaderView.ResizeToContents)  # 客户ID
        header.setSectionResizeMode(4, QHeaderView.ResizeToContents)  # 开户金额
        header.setSectionResizeMode(5, QHeaderView.ResizeToContents)  # 余额
        header.setSectionResizeMode(6, QHeaderView.ResizeToContents)  # 是否挂失

        layout.addLayout(btn_layout)
        layout.addWidget(self.table)
        self.setLayout(layout)

        # 连接信号
        self.add_btn.clicked.connect(self.add_card)
        self.edit_btn.clicked.connect(self.edit_card)
        self.delete_btn.clicked.connect(self.delete_card)
        self.refresh_btn.clicked.connect(self.refresh_cards)  # 改为使用refresh_cards方法
        self.export_btn.clicked.connect(self.export_report)

    # === 新增查询功能 ===
    def search_cards(self):
        """执行基本搜索"""
        keyword = self.search_input.text().strip()
        if not keyword:
            self.load_cards()
            return

        self.status_label.setText("正在搜索...")
        QApplication.processEvents()

        try:
            query = """
            SELECT c.*, d.savingName 
            FROM cardInfo c
            JOIN deposit d ON c.savingID = d.savingID
            WHERE c.cardID LIKE %s 
               OR c.customerID LIKE %s
               OR c.curID LIKE %s
            ORDER BY c.cardID
            """
            cards = self.manager.db.execute_query(
                query,
                (f"%{keyword}%", f"%{keyword}%", f"%{keyword}%")
            )

            if cards:
                self.display_cards(cards)
                self.status_label.setText(f"找到 {len(cards)} 条结果")
            else:
                self.status_label.setText("没有找到匹配的银行卡")
                QMessageBox.information(self, "提示", "没有找到匹配的银行卡")

        except Exception as e:
            self.status_label.setText("搜索失败")
            QMessageBox.critical(self, "错误", f"搜索失败: {str(e)}")

    def show_advanced_search(self):
        """显示高级搜索对话框"""
        dialog = AdvancedSearchDialog(self)
        if dialog.exec_() == QDialog.Accepted:
            self.execute_advanced_search(dialog.get_search_params())

    def execute_advanced_search(self, params):
        """执行高级搜索（修复余额范围查询）"""
        if params is None:  # 新增参数检查
            return

        self.status_label.setText("正在执行高级搜索...")
        QApplication.processEvents()

        try:
            # 构建基础查询
            query = """
            SELECT c.*, d.savingName 
            FROM cardInfo c
            JOIN deposit d ON c.savingID = d.savingID
            WHERE 1=1
            """
            query_params = []

            # === 修复的查询条件构建 ===
            # 卡号模糊查询
            if params.get('card_id'):
                query += " AND c.cardID LIKE %s"
                query_params.append(f"%{params['card_id']}%")

            # 客户ID精确查询
            if params.get('customer_id'):
                query += " AND c.customerID = %s"
                query_params.append(params['customer_id'])

            # 货币类型精确查询
            if params.get('currency_type'):
                query += " AND c.curID = %s"
                query_params.append(params['currency_type'])

            # 存款类型精确查询
            if params.get('deposit_type'):
                query += " AND c.savingID = %s"
                query_params.append(params['deposit_type'])

            # 是否挂失精确查询
            if params.get('is_report_loss'):
                query += " AND c.IsReportLoss = %s"
                query_params.append(params['is_report_loss'])

            # === 修复的余额范围查询 ===
            if params.get('min_balance') is not None:
                query += " AND c.balance >= %s"
                query_params.append(float(params['min_balance']))

            if params.get('max_balance') is not None:
                query += " AND c.balance <= %s"
                query_params.append(float(params['max_balance']))

            query += " ORDER BY c.cardID"

            # 执行查询
            cards = self.manager.db.execute_query(query, query_params)

            if cards:
                self.display_cards(cards)
                self.status_label.setText(f"找到 {len(cards)} 条结果")
            else:
                self.status_label.setText("没有找到匹配的银行卡")
                QMessageBox.information(self, "提示", "没有找到符合条件的银行卡")

        except Exception as e:
            self.status_label.setText("高级搜索失败")
            QMessageBox.critical(self, "错误", f"高级搜索失败: {str(e)}")
            traceback.print_exc()

    def display_cards(self, cards):
        """通用方法：显示银行卡列表"""
        self.table.setRowCount(len(cards))

        for row, card in enumerate(cards):
            items = [
                card.get('cardID', ''),
                card.get('curID', ''),
                card.get('savingName', '未知类型'),
                str(card.get('customerID', '')),
                f"{card.get('openMoney', 0):.2f}",
                f"{card.get('balance', 0):.2f}",
                card.get('IsReportLoss', '否')
            ]

            for col, value in enumerate(items):
                item = QTableWidgetItem(value)
                item.setTextAlignment(Qt.AlignCenter)
                if col == 6 and value == "是":
                    item.setForeground(QBrush(QColor(255, 0, 0)))
                self.table.setItem(row, col, item)

        # 更新按钮状态
        has_data = len(cards) > 0
        self.edit_btn.setEnabled(has_data)
        self.delete_btn.setEnabled(has_data)

    # === 查询功能结束 ===

    def load_cards(self, force_refresh=False):
        """加载银行卡数据 - 增加强制刷新选项"""
        self.status_label.setText("正在加载数据...")
        QApplication.processEvents()

        try:
            # 清除缓存
            if force_refresh:
                self.clear_caches()

            if self.customer_id:
                cards = self.manager.get_customer_cards(self.customer_id)
            else:
                cards = self.manager.list_all_cards()

            if cards:
                self.display_cards(cards)
                self.status_label.setText(f"加载成功，共 {len(cards)} 条记录")
            else:
                self.status_label.setText("没有银行卡数据")

        except Exception as e:
            self.status_label.setText("加载失败")
            QMessageBox.critical(self, "错误", f"加载银行卡数据失败: {str(e)}")

    def add_card(self):
        """添加银行卡"""
        # 不强制要求customer_id
        dialog = CardDialog(customer_id=self.customer_id, parent=self)
        if dialog.exec_() == QDialog.Accepted:
            values = dialog.get_values()
            if not values['customer_id']:
                QMessageBox.warning(self, "警告", "请确保表单中填写了客户ID")
                return

            if self.manager.add_card(**values):
                QMessageBox.information(self, "成功", "银行卡添加成功")
                self.load_cards()
            else:
                QMessageBox.warning(
                    self,
                    "添加银行卡失败",
                    "添加银行卡失败!请检查以下信息:\n\n"
                    "1. 卡号必须以 '10103576' 开头\n"
                    "2. 客户ID必须存在于系统中\n"
                    "3. 请确认卡号长度必须是16位数字\n"
                )

    def edit_card(self):
        """编辑银行卡信息 - 修复validate_card_data问题"""
        try:
            card_id = self.get_selected_card_id()
            if not card_id:
                QMessageBox.warning(self, "警告", "请先选择要编辑的银行卡")
                return

            # 获取银行卡信息
            card = self.manager.get_card_by_id(card_id)
            if not card:
                QMessageBox.warning(self, "错误", "找不到指定的银行卡")
                return

            # 创建编辑对话框
            dialog = CardDialog(card=card, parent=self)
            if dialog.exec_() == QDialog.Accepted:
                # 准备更新参数
                new_values = dialog.get_values()

                # 验证银行卡数据（使用新添加的方法）
                if not self.validate_card_data(new_values):
                    return

                # 准备更新参数
                update_params = {
                    'cur_id': new_values['cur_id'],
                    'saving_id': new_values['saving_id'],
                    'balance': new_values['balance'],
                    'password': new_values['password'],
                    'is_report_loss': new_values['is_report_loss']
                }

                # 执行更新
                try:
                    if self.manager.update_card(card_id, **update_params):
                        QMessageBox.information(self, "成功", "银行卡信息更新成功")
                        self.load_cards()  # 刷新表格
                    else:
                        QMessageBox.warning(self, "失败", "更新银行卡信息失败")
                except Exception as e:
                    QMessageBox.critical(self, "错误", f"更新银行卡时发生错误: {str(e)}")
                    print(f"更新银行卡错误: {traceback.format_exc()}")

        except Exception as e:
            QMessageBox.critical(self, "严重错误", f"执行编辑操作时发生未处理异常: {str(e)}")
            print(f"编辑银行卡时崩溃: {traceback.format_exc()}")

    def validate_card_data(self, card_data):
        """验证银行卡数据有效性 - 新添加的方法"""
        # 检查所有必需字段是否存在
        required_fields = ['cur_id', 'saving_id', 'balance', 'password', 'is_report_loss']
        for field in required_fields:
            if field not in card_data or card_data[field] is None:
                QMessageBox.warning(self, "错误", f"缺少必需字段: {field}")
                return False

        # 检查余额是否为有效数值
        try:
            balance = float(card_data['balance'])
            if balance <= 0:
                QMessageBox.warning(self, "错误", "余额必须大于0")
                return False
        except (ValueError, TypeError):
            QMessageBox.warning(self, "错误", f"无效的余额值: {card_data['balance']}")
            return False

        # 检查密码长度
        if len(card_data['password']) < 6:
            QMessageBox.warning(self, "错误", "密码长度不能少于6位")
            return False

        # 检查挂失状态
        if card_data['is_report_loss'] not in ['是', '否']:
            QMessageBox.warning(self, "错误", "挂失状态必须是'是'或'否'")
            return False

        return True

    def delete_card(self):
        """删除银行卡 - 增加余额转移功能"""
        card_id = self.get_selected_card_id()
        if not card_id:
            QMessageBox.warning(self, "警告", "请先选择要删除的银行卡")
            return

        try:
            # 获取银行卡信息
            card_info = self.manager.get_card_by_id(card_id)
            if not card_info:
                QMessageBox.warning(self, "错误", "找不到指定的银行卡")
                return

            balance = card_info.get('balance', 0)

            # 如果余额大于0，需要转移余额
            if balance > 0:
                # 显示余额转移对话框
                transfer_dialog = BalanceTransferDialog(
                    card_id=card_id,
                    balance=balance,
                    parent=self
                )

                if transfer_dialog.exec_() != QDialog.Accepted:
                    return  # 用户取消了操作

                # 获取目标卡号
                target_card_id = transfer_dialog.get_target_card_id()
                if not target_card_id:
                    QMessageBox.warning(self, "错误", "必须指定目标银行卡")
                    return

                # 验证目标卡号
                target_card = self.manager.get_card_by_id(target_card_id)
                if not target_card:
                    QMessageBox.warning(self, "错误", f"目标银行卡 {target_card_id} 不存在")
                    return

                if target_card['IsReportLoss'] == '是':
                    QMessageBox.warning(self, "错误", f"目标银行卡 {target_card_id} 已挂失")
                    return

                # 执行余额转移
                success, message = self.transfer_balance(
                    from_card_id=card_id,
                    to_card_id=target_card_id,
                    amount=balance
                )

                if not success:
                    QMessageBox.warning(self, "余额转移失败", message)
                    return

            # 确认删除
            reply = QMessageBox.question(
                self, "确认删除",
                f"确定要删除银行卡 {card_id} 吗？此操作不可恢复！",
                QMessageBox.Yes | QMessageBox.No
            )

            if reply == QMessageBox.Yes:
                # 使用CardManager的delete_card方法
                if self.manager.delete_card(card_id):
                    QMessageBox.information(self, "成功", "银行卡删除成功")
                    self.load_cards()
                else:
                    QMessageBox.warning(self, "失败", "删除银行卡失败，可能有关联交易")

        except Exception as e:
            QMessageBox.critical(self, "错误", f"删除银行卡时出错: {str(e)}")

    def transfer_balance(self, from_card_id, to_card_id, amount):
        """将余额转移到另一张银行卡"""
        try:
            # 开启事务
            cursor = self.manager.db.connection.cursor()
            cursor.execute("START TRANSACTION")

            # 1. 从原卡扣款
            update_from_query = """
            UPDATE cardInfo 
            SET balance = balance - %s 
            WHERE cardID = %s
            """
            cursor.execute(update_from_query, (amount, from_card_id))
            if cursor.rowcount == 0:
                cursor.execute("ROLLBACK")
                return False, "原卡更新失败"

            # 2. 向目标卡加款
            update_to_query = """
            UPDATE cardInfo 
            SET balance = balance + %s 
            WHERE cardID = %s
            """
            cursor.execute(update_to_query, (amount, to_card_id))
            if cursor.rowcount == 0:
                cursor.execute("ROLLBACK")
                return False, "目标卡更新失败"

            # 3. 记录转出交易
            trade_id = self.manager._generate_trade_id()
            insert_out_query = """
            INSERT INTO tradeInfo 
            (cardID, tradeDate, tradeType, transactionID, tradeMoney, remark)
            VALUES (%s, NOW(), '余额转移', %s, %s, %s)
            """
            cursor.execute(
                insert_out_query,
                (from_card_id, trade_id, -amount, f"删除银行卡余额转移到 {to_card_id}")
            )

            # 4. 记录转入交易
            insert_in_query = """
            INSERT INTO tradeInfo 
            (cardID, tradeDate, tradeType, transactionID, tradeMoney, remark)
            VALUES (%s, NOW(), '余额转入', %s, %s, %s)
            """
            cursor.execute(
                insert_in_query,
                (to_card_id, trade_id, amount, f"来自 {from_card_id} 的余额转移")
            )

            # 提交事务
            cursor.execute("COMMIT")
            return True, f"成功转移 ¥{amount:.2f} 到卡号 {to_card_id}"

        except Exception as e:
            try:
                cursor.execute("ROLLBACK")
            except:
                pass
            return False, f"余额转移失败: {str(e)}"

        finally:
            if cursor:
                cursor.close()

    def clear_caches(self):
        """清除所有可能的缓存"""
        # 清除管理器缓存
        if hasattr(self.manager, 'cached_cards'):
            del self.manager.cached_cards

        # 清除数据库连接状态
        try:
            if self.manager.db.connection:
                self.manager.db.connection.commit()
                self.manager.db.connection.reset_session()
        except:
            pass

    def refresh_cards(self):
        """刷新银行卡数据 - 强制重新加载"""
        self.load_cards(force_refresh=True)

    def export_report(self):
        """导出银行卡报表"""
        try:
            # 获取当前银行卡数据
            data = self.get_current_card_data()

            if not data:
                QMessageBox.warning(self, "导出失败", "没有银行卡数据可供导出")
                return

            # 转换为DataFrame
            df = pd.DataFrame(data)

            # 重命名列（中文表头）
            column_mapping = {
                'cardID': '卡号',
                'curID': '货币类型',
                'savingName': '存款类型',
                'customerID': '客户ID',
                'openMoney': '开户金额',
                'balance': '余额',
                'IsReportLoss': '是否挂失'
            }
            df = df.rename(columns=column_mapping)

            # 设置默认文件名
            current_date = datetime.now().strftime("%Y%m%d_%H%M")
            default_filename = f"银行卡报表_{current_date}.xlsx"

            # 让用户选择保存位置
            file_path, selected_filter = QFileDialog.getSaveFileName(
                self,
                "导出银行卡报表",
                os.path.join(os.path.expanduser("~"), "Downloads", default_filename),
                "Excel 文件 (*.xlsx);;CSV 文件 (*.csv)"
            )

            if not file_path:
                return  # 用户取消了导出

            # 根据选择的文件类型进行导出
            if "csv" in selected_filter.lower():
                # 导出为CSV
                self.export_to_csv(df, file_path)
            else:
                # 确保扩展名为xlsx
                if not file_path.lower().endswith('.xlsx'):
                    file_path += '.xlsx'

                # 导出为Excel
                self.export_to_excel(df, file_path)

            # 显示成功消息
            QMessageBox.information(
                self,
                "导出成功",
                f"银行卡报表已成功导出！\n\n保存位置: {file_path}"
            )

        except Exception as e:
            QMessageBox.critical(
                self,
                "导出失败",
                f"导出报表时发生错误:\n{str(e)}"
            )

    def get_current_card_data(self):
        """从数据库获取当前银行卡数据"""
        # 获取当前搜索条件
        search_keyword = self.get_current_search_keyword()
        advanced_params = self.get_current_advanced_params()

        # 调用CardManager获取数据
        card_manager = CardManager()
        return card_manager.get_current_cards(search_keyword, advanced_params)

    def export_to_excel(self, df, file_path):
        """将银行卡数据导出为格式化的Excel文件"""
        # 创建Excel写入器
        writer = pd.ExcelWriter(file_path, engine='openpyxl')
        df.to_excel(writer, index=False, sheet_name='银行卡列表')

        # 获取Excel工作表对象
        workbook = writer.book
        worksheet = writer.sheets['银行卡列表']

        # 设置列宽
        column_widths = {
            '卡号': 20,
            '货币类型': 12,
            '存款类型': 15,
            '客户ID': 10,
            '开户金额': 15,
            '余额': 15,
            '是否挂失': 10
        }

        # 设置列宽
        for col_idx, col_name in enumerate(df.columns, 1):
            col_letter = openpyxl.utils.get_column_letter(col_idx)
            worksheet.column_dimensions[col_letter].width = column_widths.get(col_name, 12)

        # 设置标题行样式
        header_fill = PatternFill(
            start_color="1F497D",
            end_color="1F497D",
            fill_type="solid"
        )
        header_font = Font(color="FFFFFF", bold=True)
        header_alignment = Alignment(horizontal="center", vertical="center")

        # 应用标题行样式
        for cell in worksheet[1]:
            cell.fill = header_fill
            cell.font = header_font
            cell.alignment = header_alignment

        # 设置数据行格式
        data_alignment = Alignment(horizontal="right", vertical="center")
        thin_border = Border(
            left=Side(style='thin'),
            right=Side(style='thin'),
            top=Side(style='thin'),
            bottom=Side(style='thin')
        )

        # 货币格式
        currency_format = '"¥"#,##0.00_);("¥"#,##0.00)'

        # 设置数据行格式
        for row in worksheet.iter_rows(min_row=2, max_row=worksheet.max_row, min_col=1, max_col=len(df.columns)):
            for cell in row:
                cell.alignment = data_alignment
                cell.border = thin_border

                # 金额列设置货币格式
                col_name = df.columns[cell.column - 1]
                if col_name in ['开户金额', '余额']:
                    cell.number_format = currency_format

        # 添加报表标题
        worksheet.insert_rows(1)
        worksheet.merge_cells(start_row=1, start_column=1, end_row=1, end_column=len(df.columns))

        title_cell = worksheet.cell(row=1, column=1)
        title_cell.value = "银行卡管理系统 - 银行卡报表"
        title_cell.font = Font(bold=True, size=16)
        title_cell.alignment = Alignment(horizontal="center")

        # 添加导出时间
        export_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        last_row = worksheet.max_row + 1
        worksheet.cell(row=last_row, column=1).value = f"导出时间: {export_time}"
        worksheet.merge_cells(start_row=last_row, start_column=1, end_row=last_row, end_column=len(df.columns))

        # 保存Excel文件
        workbook.save(file_path)

    def export_to_csv(self, df, file_path):
        """将银行卡数据导出为CSV文件"""
        # 生成CSV内容
        csv_content = "卡号,货币类型,存款类型,客户ID,开户金额,余额,是否挂失\n"

        for _, row in df.iterrows():
            csv_row = f"{row['卡号']},{row['货币类型']},{row['存款类型']},{row['客户ID']},"
            csv_row += f"{row['开户金额']:.2f},{row['余额']:.2f},{row['是否挂失']}\n"
            csv_content += csv_row

        # 保存为CSV文件
        with open(file_path, 'w', encoding='utf-8-sig') as f:
            f.write(csv_content)

    def get_current_search_keyword(self):
        """获取当前基本搜索关键字"""
        if hasattr(self, 'search_input') and self.search_input.text().strip():
            return self.search_input.text().strip()
        return None

    def get_current_advanced_params(self):
        """获取当前高级搜索参数"""
        if hasattr(self, 'current_search_params') and self.current_search_params:
            return self.current_search_params
        return None

class BalanceTransferDialog(QDialog):
    """余额转移对话框"""

    def __init__(self, card_id, balance, parent=None):
        super().__init__(parent)
        self.card_id = card_id
        self.balance = balance
        self.setWindowTitle(f"银行卡余额转移 (¥{balance:.2f})")
        self.setFixedSize(500, 300)
        self.setup_ui()

    def setup_ui(self):
        """初始化界面"""
        layout = QVBoxLayout()
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(15)

        # 信息提示
        info_label = QLabel(
            f"银行卡 <b>{self.card_id}</b> 有余额 <b>¥{self.balance:.2f}</b>。\n"
            "请选择一张有效的银行卡来接收这些余额。"
        )
        info_label.setWordWrap(True)
        layout.addWidget(info_label)

        # 目标卡号输入
        form_layout = QFormLayout()
        self.target_card_input = QLineEdit()
        self.target_card_input.setPlaceholderText("请输入16位目标银行卡号")
        self.target_card_input.setMaxLength(16)

        # 验证按钮
        self.verify_btn = QPushButton("验证卡号")
        self.verify_btn.clicked.connect(self.verify_target_card)

        # 目标卡信息
        self.target_card_info = QLabel()
        self.target_card_info.setWordWrap(True)
        self.target_card_info.setStyleSheet("color: #666; font-style: italic;")

        # 布局
        target_layout = QHBoxLayout()
        target_layout.addWidget(self.target_card_input)
        target_layout.addWidget(self.verify_btn)

        form_layout.addRow("目标银行卡号:", target_layout)
        form_layout.addRow("卡号信息:", self.target_card_info)
        layout.addLayout(form_layout)

        # 按钮
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)

        self.setLayout(layout)

    def verify_target_card(self):
        """验证目标银行卡"""
        target_card_id = self.target_card_input.text().strip()

        if not target_card_id:
            self.target_card_info.setText("请输入银行卡号")
            return

        if len(target_card_id) != 16 or not target_card_id.isdigit():
            self.target_card_info.setText("银行卡号必须是16位数字")
            return

        if target_card_id == self.card_id:
            self.target_card_info.setText("不能选择同一张银行卡")
            return

        # 获取银行卡信息
        try:
            manager = CardManager()
            card_info = manager.get_card_by_id(target_card_id)

            if not card_info:
                self.target_card_info.setText("银行卡不存在")
                return

            if card_info['IsReportLoss'] == '是':
                self.target_card_info.setText("银行卡已挂失，不能接收余额")
                return

            # 显示银行卡信息
            info_text = (
                f"持卡人: 客户ID {card_info.get('customerID', '未知')}\n"
                f"余额: ¥{card_info.get('balance', 0):.2f}\n"
                f"状态: {'正常' if card_info.get('IsReportLoss', '否') == '否' else '已挂失'}"
            )
            self.target_card_info.setText(info_text)

        except Exception as e:
            self.target_card_info.setText(f"验证失败: {str(e)}")

    def get_target_card_id(self):
        """获取目标银行卡号"""
        return self.target_card_input.text().strip()

class AdvancedSearchDialog(QDialog):
    """高级搜索对话框 - 恢复存款类型管理功能"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("高级搜索条件")
        self.setFixedSize(800, 800)  # 增加高度以容纳新字段
        self.setup_ui()

        # 初始化存款类型管理器
        self.deposit_manager = DepositManager()

        # 加载存款类型
        self.load_deposit_types()

        # 设置样式
        self.setStyleSheet("""
            QDialog {
                font-family: "Microsoft YaHei";
            }
            QLabel {
                min-width: 80px;
            }
            QLineEdit, QComboBox, QDoubleSpinBox {
                padding: 5px;
                min-width: 150px;
            }
            .balance-range {
                background-color: #f9f9f9;
                border: 1px solid #ddd;
                border-radius: 4px;
                padding: 8px;
            }
            .balance-label {
                font-weight: bold;
                color: #444;
            }
        """)

    def setup_ui(self):
        """初始化界面 - 恢复存款类型管理按钮"""
        layout = QFormLayout()
        layout.setSpacing(10)
        layout.setContentsMargins(15, 15, 15, 15)

        # 卡号输入
        self.card_id_input = QLineEdit()
        self.card_id_input.setPlaceholderText("支持模糊查询")
        layout.addRow("卡号:", self.card_id_input)

        # 客户ID输入
        self.customer_id_input = QLineEdit()
        self.customer_id_input.setPlaceholderText("输入客户ID")
        layout.addRow("客户ID:", self.customer_id_input)

        # 货币类型下拉
        self.currency_combo = QComboBox()
        self.currency_combo.addItems(["", "RMB(￥)", "USD($)", "JPY(￥)"])
        layout.addRow("货币类型:", self.currency_combo)

        # === 存款类型行 + 管理按钮 ===
        deposit_type_layout = QHBoxLayout()

        # 存款类型下拉
        self.deposit_combo = QComboBox()
        deposit_type_layout.addWidget(self.deposit_combo)

        # 存款类型管理按钮 (恢复功能)
        self.manage_deposit_btn = QPushButton("管理存款类型...")
        self.manage_deposit_btn.setFixedWidth(120)
        self.manage_deposit_btn.clicked.connect(self.manage_deposit_types)
        deposit_type_layout.addWidget(self.manage_deposit_btn)

        layout.addRow("存款类型:", deposit_type_layout)

        # 是否挂失下拉
        self.report_loss_combo = QComboBox()
        self.report_loss_combo.addItems(["", "是", "否"])
        layout.addRow("是否挂失:", self.report_loss_combo)

        # === 余额范围查询区域 ===
        balance_group = QGroupBox("余额范围")
        balance_group.setStyleSheet("QGroupBox { border: 1px solid #ddd; margin-top: 10px; padding-top: 20px; }")
        balance_layout = QFormLayout()

        # 最小余额
        min_balance_layout = QHBoxLayout()
        self.min_balance_spin = QDoubleSpinBox()
        self.min_balance_spin.setRange(0, 1000000)
        self.min_balance_spin.setDecimals(2)
        self.min_balance_spin.setPrefix("¥ ")
        self.min_balance_spin.setValue(0)
        min_balance_layout.addWidget(QLabel("最小:"))
        min_balance_layout.addWidget(self.min_balance_spin)
        balance_layout.addRow(min_balance_layout)

        # 最大余额
        max_balance_layout = QHBoxLayout()
        self.max_balance_spin = QDoubleSpinBox()
        self.max_balance_spin.setRange(0, 1000000)
        self.max_balance_spin.setDecimals(2)
        self.max_balance_spin.setPrefix("¥ ")
        self.max_balance_spin.setValue(10000)
        max_balance_layout.addWidget(QLabel("最大:"))
        max_balance_layout.addWidget(self.max_balance_spin)
        balance_layout.addRow(max_balance_layout)

        # 添加启用/禁用复选框
        self.enable_balance_range = QCheckBox("启用余额范围查询")
        self.enable_balance_range.setChecked(False)
        self.enable_balance_range.toggled.connect(self.toggle_balance_range)
        balance_layout.addRow(self.enable_balance_range)

        balance_group.setLayout(balance_layout)
        layout.addRow(balance_group)

        # 禁用初始状态
        self.toggle_balance_range(False)
        # === 余额范围区域结束 ===

        # 按钮组
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        layout.addRow(button_box)

        self.setLayout(layout)

        # 连接信号
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)

    def load_deposit_types(self):
        """加载存款类型到下拉框 - 完整功能"""
        try:
            self.deposit_combo.clear()
            self.deposit_combo.addItem("", userData=None)  # 空选项

            deposit_types = self.deposit_manager.get_all_deposit_types()
            for deposit in deposit_types:
                # 在显示中添加描述信息
                display_text = f"{deposit['savingName']} (ID:{deposit['savingID']})"
                if deposit.get('descrip'):
                    display_text += f" - {deposit['descrip']}"

                self.deposit_combo.addItem(
                    display_text,
                    userData=deposit['savingID']
                )

        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载存款类型失败: {str(e)}")

    def manage_deposit_types(self):
        """打开存款类型管理对话框 - 恢复功能"""
        dialog = DepositTypeDialog(self)
        if dialog.exec_() == QDialog.Accepted:
            self.load_deposit_types()  # 刷新下拉框

    def toggle_balance_range(self, enabled):
        """启用/禁用余额范围输入控件"""
        self.min_balance_spin.setEnabled(enabled)
        self.max_balance_spin.setEnabled(enabled)

    def get_search_params(self):
        """获取搜索参数 - 完整参数集"""
        params = {
            'card_id': self.card_id_input.text().strip(),
            'customer_id': self.customer_id_input.text().strip(),
            'currency_type': self.currency_combo.currentText(),
            'deposit_type': self.deposit_combo.currentData(),
            'is_report_loss': self.report_loss_combo.currentText()
        }

        # 添加余额范围参数（如果启用）
        if self.enable_balance_range.isChecked():
            params['min_balance'] = self.min_balance_spin.value()
            params['max_balance'] = self.max_balance_spin.value()

        return params

class AdminDashboard(QMainWindow):
    """主窗口 - 银行卡管理"""

    def __init__(self, customer_id=None):
        super().__init__()
        self.setWindowTitle("银行卡管理系统")
        self.setMinimumSize(1000, 600)

        # 创建银行卡管理标签页
        self.card_tab = CardManagementTab(customer_id=customer_id)
        self.setCentralWidget(self.card_tab)


if __name__ == "__main__":
    app = QApplication(sys.argv)

    # 设置全局字体
    font = QFont()
    font.setFamily("Microsoft YaHei" if sys.platform == 'win32' else "Arial")
    font.setPointSize(10)
    app.setFont(font)

    # 可选的客户ID参数
    customer_id = None
    if len(sys.argv) > 1:
        try:
            customer_id = int(sys.argv[1])
        except ValueError:
            pass

    window = AdminDashboard(customer_id=customer_id)
    window.show()
    sys.exit(app.exec_())